package org.NooLab.texx.tcp.box.agents;

import java.util.Observable;
import java.util.Observer;
 
import org.NooLab.texx.tcp.box.TcpBox;
import org.NooLab.texx.tcp.box.agents.data.Data;
import org.NooLab.texx.tcp.box.agents.data.DataIntf;
import org.NooLab.texx.tcp.box.infra.DataReceiverIntf;
import org.NooLab.texx.tcp.box.infra.DataSenderIntf;
import org.NooLab.utilities.logging.PrintLog;
import org.NooLab.utilities.net.GUID;
import org.NooLab.utilities.objects.StringedObjects;



public class TexxClient {

	 
	public static void main(String[] args) {
		
		
		(new TcpPrimaryClient(7210, 7209)).start(); // for testing in standalone mode
	}

}



class TcpPrimaryClient{

	int senderPort ; 
	int listeningPort ;
	
	TcpBox tcpBox;
	
	DataReceiverIntf receiverDevice;
	DataSenderIntf senderDevice;
	
	MessageReceiver msgReceiver;

	StringedObjects sob = new StringedObjects();
	PrintLog out = new PrintLog(2,true);
	
	// ========================================================================
	public TcpPrimaryClient( int senderPort, int listeningPort ){
		
		this.senderPort = senderPort;
		this.listeningPort = listeningPort ;
	
		tcpBox = new TcpBox();
		
		
		msgReceiver = new MessageReceiver(); 
	}
	// ========================================================================
	
	
	public void start( ) {
		
		
		receiverDevice = tcpBox.createReceiver(listeningPort, senderPort, msgReceiver, "") ;
		senderDevice   = tcpBox.createSender(senderPort, listeningPort, "") ;
		
		testLoop(1) ;
	}
	
	
	private void testLoop(int n) {
		DataIntf data;
		String suid;
		
		for (int i=0;i<n;i++){
			data = new Data(i+1);
			suid = GUID.randomvalue() ;
			
			// here we send the data using an external GUID,
			// of course, the GUID could also be part of the data object itself
			out.print(2, "C sending "+(i+1)+"  with id <"+suid+">");
			String pmsg = sob.encode(data);
			
			senderDevice.send( pmsg,suid );
			
			out.delay(500);
		}
	}


	class MessageReceiver implements Observer{

		@Override
		public void update(Observable srv, Object dataObj) {
		 	
			String[] dataPkg;
			dataPkg = (String[])dataObj ;
			
			out.print(4, "C: "+srv.toString().replace("org.NooLab.", "")) ;
			
			 
			DataIntf data = (DataIntf)sob.decode( (String)dataPkg[1] );
			Object obj = data.getObject();
			int v = (Integer)obj  ;
			
			out.print(4,"client received changed data : "+v +" for id <"+dataPkg[0]+">"); 
		}
		
	}
	
}